package com.unittec.zk.provider.exam.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unittec.zk.provider.exam.entity.ElQuRepo;
import com.unittec.zk.provider.exam.mapper.ElQuRepoMapper;
import org.springframework.util.CollectionUtils;

@Service
public class ElQuRepoService extends ServiceImpl<ElQuRepoMapper, ElQuRepo> {

    @Resource
    private ElRepoService elRepoService;

    public void saveAll(String quId, Integer quType, List<String> ids) {
        // 先删除
        QueryWrapper<ElQuRepo> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ElQuRepo::getQuId, quId);
        this.remove(wrapper);

        // 保存全部
        if(!CollectionUtils.isEmpty(ids)){
            List<ElQuRepo> list = new ArrayList<>();
            for(String id: ids){
                ElQuRepo ref = new ElQuRepo();
                ref.setQuId(quId);
                ref.setRepoId(id);
                ref.setQuType(quType);
                list.add(ref);
            }
            this.saveBatch(list);


            for(String id: ids){
                this.sortRepo(id);
            }
        }
    }

    /**
     * 单个题库进行排序
     * @param repoId
     */
    public void sortRepo(String repoId){

        QueryWrapper<ElQuRepo> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ElQuRepo::getRepoId, repoId);

        List<ElQuRepo> list = this.list(wrapper);
        if(CollectionUtils.isEmpty(list)){
            return;
        }

        int sort = 1;
        for(ElQuRepo item: list){
            item.setSort(sort);
            sort++;
        }
        this.updateBatchById(list);

        // 更新统计数量
        elRepoService.refreshStat(repoId);
    }
}
